package parser

import (
	"fmt"

	"github.com/spf13/cast"
	"vitess.io/vitess/go/vt/sqlparser"
)

func convertInsert(i *sqlparser.Insert, query string) (Statement, error) {
	cols := i.Columns
	if cols == nil {
		return nil, fmt.Errorf("unsupported syntax: column name cannot be empty, near '%s'", i.Table.Name.String())
	}
	stmt := &InsertStatement{
		db:  i.Table.Qualifier.String(),
		tbl: i.Table.Name.String(),
	}
	stmt.sql = query
	for _, c := range cols {
		stmt.columns = append(stmt.columns, c.String())
	}
	rs, ok := i.Rows.(sqlparser.Values)
	if !ok {
		return nil, fmt.Errorf("unsupported syntax: near 'values'")
	}
	for _, r := range rs {
		row := []interface{}{}
		for _, field := range r {
			v := field.(*sqlparser.Literal)
			switch v.Type {
			case sqlparser.IntVal:
				row = append(row, cast.ToInt(v.Val))
			case sqlparser.DecimalVal:
				row = append(row, cast.ToFloat64(v.Val))
			default:
				row = append(row, v.Val)
			}
		}
		stmt.rows = append(stmt.rows, row)
	}
	return stmt, nil
}

type InsertStatement struct {
	BaseStatement
	db      string
	tbl     string
	columns []string
	rows    [][]interface{}
}

func (s *InsertStatement) Database() string {
	return s.db
}

func (s *InsertStatement) Table() string {
	return s.tbl
}

func (s *InsertStatement) Columns() []string {
	return s.columns
}

func (s *InsertStatement) Rows() [][]interface{} {
	return s.rows
}
